import { Injectable } from '@angular/core'

export interface UserInfo {
  username: string
  role: string
  name: string
  loginTime: string
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isInitialized = false
  private cachedAuthStatus: boolean | null = null

  constructor() {}

  // 初始化认证状态
  initAuth(): void {
    if (this.isInitialized) return
    this.cachedAuthStatus = localStorage.getItem('isLoggedIn') === 'true'
    this.isInitialized = true
  }

  // 检查用户是否已登录
  isAuthenticated(): boolean {
    if (!this.isInitialized) {
      this.initAuth()
    }
    return this.cachedAuthStatus === true
  }

  // 获取当前用户信息
  getCurrentUser(): UserInfo | null {
    if (!this.isAuthenticated()) return null

    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        return JSON.parse(userInfoStr)
      } catch (e) {
        console.error('解析用户信息失败:', e)
        this.clearAuthToken()
        return null
      }
    }
    return null
  }

  // 设置登录状态
  setAuthToken(userInfo: any): void {
    localStorage.setItem('isLoggedIn', 'true')
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    this.cachedAuthStatus = true
  }

  // 清除登录状态
  clearAuthToken(): void {
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('userInfo')
    this.cachedAuthStatus = false
    this.isInitialized = false
  }

  // 检查用户权限
  hasPermission(permission: string): boolean {
    const user = this.getCurrentUser()
    if (!user) return false

    if (user.role === 'admin') return true

    const userPermissions: Record<string, string[]> = {
      user: ['read', 'create', 'update']
    }

    return userPermissions[user.role]?.includes(permission) ?? false
  }

  // 格式化登录时间
  formatLoginTime(timeStr?: string): string {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // 模拟登录验证（演示用）
  validateCredentials(username: string, password: string): {
    success: boolean,
    user?: UserInfo,
    message?: string
  } {
    const validUsers: Record<string, { password: string, role: string, name: string }> = {
      admin: { password: '123456', role: 'admin', name: '系统管理员' },
      user: { password: '123456', role: 'user', name: '普通用户' }
    }

    const user = validUsers[username]
    if (user && user.password === password) {
      return {
        success: true,
        user: {
          username,
          role: user.role,
          name: user.name,
          loginTime: new Date().toISOString()
        }
      }
    }

    return {
      success: false,
      message: '用户名或密码错误'
    }
  }
}
